package com.atguigu.controller;


import com.atguigu.client.CartFeignClient;
import com.atguigu.client.UserFeignClient;
import com.atguigu.constant.MqConst;
import com.atguigu.entity.CartInfo;
import com.atguigu.entity.OrderDetail;
import com.atguigu.entity.OrderInfo;
import com.atguigu.entity.UserAddress;
import com.atguigu.result.RetVal;
import com.atguigu.service.OrderInfoService;
import com.atguigu.util.AuthContextHolder;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.*;

/**
 * <p>
 * 订单表 订单表 前端控制器
 * </p>
 *
 * @author GuoJH
 * @since 2021-09-07
 */
@RestController
@RequestMapping("/order")
public class OrderInfoController {
    @Autowired
    private UserFeignClient userFeignClient;
    @Autowired
    private CartFeignClient cartFeignClient;
    @Autowired
    private OrderInfoService orderInfoService;

    //购物车的结算 生成订单信息显示到页面
    @GetMapping("/confirm")
    public RetVal<Map<String, Object>> confirm(HttpServletRequest request){
        //获取用户的id
        String userId = AuthContextHolder.getUserId(request);
        //远程调用通过id获取地址信息
        List<UserAddress> userAddressList = userFeignClient.queryAddressByUserId(userId);
        //远程调用获取购物车的选中信息
        List<CartInfo> selectedProductList = cartFeignClient.getSelectedProduct(userId);
        List<OrderDetail> detailArrayList = new ArrayList<>();
        BigDecimal totalMoney = new BigDecimal(0);
        Integer totalNum = 0;
        if (!CollectionUtils.isEmpty(selectedProductList)){
            for (CartInfo cartInfo : selectedProductList) {
                OrderDetail orderDetail = new OrderDetail();
                //总金额
                totalMoney = totalMoney.add(cartInfo.getCartPrice()).multiply(new BigDecimal(cartInfo.getSkuNum()));
                orderDetail.setOrderPrice(cartInfo.getCartPrice());
                orderDetail.setImgUrl(cartInfo.getImgUrl());
                orderDetail.setSkuId(cartInfo.getSkuId());
                orderDetail.setSkuName(cartInfo.getSkuName());
                orderDetail.setSkuNum(cartInfo.getSkuNum().toString());

                totalNum += cartInfo.getSkuNum();
                detailArrayList.add(orderDetail);
            }
        }
        //因为返回多个结果 封装到一个map中
        Map<String, Object> map = new HashMap<>();

        //设置交易编号 防止没有刷新页面重复提交问题(在提交之前设置,在提交时进行对比)
        String tradeNo = orderInfoService.getTradeNo(userId);

        map.put("tradeNo",tradeNo);
        map.put("userAddressList",userAddressList);//地址信息
        map.put("detailArrayList",detailArrayList);//订单中的商品清单信息
        map.put("totalNum",totalNum);//共计商品数量
        map.put("totalMoney",totalMoney);
        return RetVal.ok(map);
    }
    //提交订单(DB中保存订单的信息)
    @PostMapping("/submitOrder")
    public RetVal submitOrder(@RequestBody OrderInfo orderInfo,HttpServletRequest request){
        String userId = AuthContextHolder.getUserId(request);
        orderInfo.setUserId(Long.parseLong(userId));
        String tradeNo = request.getParameter("tradeNo");
        //验证交易编号是否一致  防止没有刷新页面重复提交
        boolean flag = orderInfoService.checkTradeNo(tradeNo,userId);
        if (!flag){
            return RetVal.fail().message("如需再次生成一个订单,请重新刷新页面提交,谢谢!");
        }
        //验证完成之后 删除掉交易编号(让每次刷新页面 都生成不一样的交易编号)
        orderInfoService.deleteTradeNo(userId);
        //验证是否还有库存  及下单前价格的变化
        //访问http://localhost:8100/hasStock?skuId=24&num=99  0:无库存  1:有库存
        List<String> retVals = orderInfoService.checkStockAndPrice(orderInfo,userId);
        if (retVals.size() > 0){//说明有数据  将list集合转位一个一个的String
            return RetVal.fail().message(StringUtils.join(retVals,","));
        }
        //保存订单信息  返回订单号
        Long orderId = orderInfoService.saveOrderInfoAndDetail(orderInfo);
        return RetVal.ok(orderId);
    }
    //根据订单id获取订单的信息
    @GetMapping("/getOrderInfo/{orderId}")
    public OrderInfo getOrderInfo(@PathVariable Long orderId){
        OrderInfo orderInfo = orderInfoService.getOrderInfo(orderId);
        return orderInfo;
    }
    //拆单 因为商家不同 仓库不同 商品不同
    @PostMapping("/splitOrder")
    public String splitOrder(@RequestParam Long orderId,@RequestParam String wareHouseIdSkuIdMap){//接受从库存系统传的参数
        return orderInfoService.splitOrder(orderId,wareHouseIdSkuIdMap);
    }
    //保存订单与详情信息  给保存秒杀订单提供接口 进行远程调用
    @PostMapping("/saveOrderInfo")
    public Long saveOrderInfo(@RequestBody OrderInfo orderInfo){
        return orderInfoService.saveOrderInfoAndDetail(orderInfo);
    }
}

